
// heart
var ctx = null;
var current_ctx = null;
var factor = {
  speed: .008, // 运动速度，值越小越慢
  t: 0 //  贝塞尔函数系数
};
var timer = null; // 循环定时器

var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fetchok:true,
    avatar: '/images/1.png',
    nickName:'zxx',
    brange_msg:'点击头像，发送弹幕。',
    style_img: {
      0:{
        style:'',
        like:2
      },
      1: {
        style: '',
        like: 12
      },
      2: {
        style: '',
        like: 11
      },
      3: {
        style: '',
        like: 123
      },
      4: {
        style: '',
        like: 1234
      },
      5: {
        style: '',
        like: 5555
      },
      6: {
        style: '',
        like: 666
      },
      7: {
        style: '',
        like: 4562
      },
      8: {
        style: '',
        like: 888
      }, 
      9: {
        style: '',
        like: 2222
      },
      10: {
        style: '',
        like: 9999
      },
      11: {
        style: '',
        like: 99999
      }
    },
    datas: [
      {
        content: "点击头像，发送弹幕。",
        id: 0,
        text_authors: "曾小仙",
        title: "发弹幕"
      }, {
        content: "参演人员:校办",
        date: "2018 / 08 / 06",
        id: 1,
        title: "节目1.舞台剧.《断臂求生》"
      }, {
        content: "参演人员:咨询中心",
        date: "2018 / 08 / 06",
        id: 2,
        title: "节目2.歌曲.《恭喜发财》"
      }, {
        content: "参演人员:长城园校区",
        date: "2018 / 08 / 06",
        id: 3,
        title: "节目3.古典舞.《繁花》",
      }, {
        content: "参演人员:云计算校区",
        date: "2018 / 08 / 06",
        id: 4,
        title: "节目4.相声.《增删改查》",
      }, {
        content: "参演人员:金融港校区",
        date: "2018 / 08 / 06",
        id: 5,
        title: "节目5.手语舞.《勇往直前》",
      }, {
        content: "参演人员:长城园校区",
        date: "2018 / 08 / 06",
        id: 6,
        title: "节目6.魔术.《魔术show》",
      }, {
        content: "参演人员:金融港校区",
        date: "2018 / 08 / 06",
        id: 7,
        title: "节目7.舞蹈.《抖音歌曲串烧》",
      }, {
        content: "参演人员:教研部",
        date: "2018 / 08 / 06",
        id: 8,
        title: "节目8.小品.《喜从天降》",
      }, {
        content: "参演人员:金融港校区",
        date: "2018 / 08 / 06",
        id: 9,
        title: "节目9.创意舞蹈.《灯光舞》",
      }, {
        content: "参演人员:金融港校区",
        date: "2018 / 08 / 06",
        id: 10,
        title: "节目10.吉他🎸弹唱.《爱一个人好难》",
      }, {
        content: "参演人员:教研部",
        date: "2018 / 08 / 06",
        id: 11,
        title: "节目11.诗歌朗诵.《断臂求生.再创辉煌》",
      }, {
        content: "参演人员:长城园校区",
        date: "2018 / 08 / 06",
        id: 12,
        title: "节目12.歌曲合唱.《光明》",
      }],
    first: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isLogin: false
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.init();
  },

  addPushHandler() {
    wx.navigateTo({
      url: '/pages/barrage/barrage',
    })
  },

  init: function () {

    wx.request({
      url: 'https://www.klxin.cn/api/v1/yearlist',
      success: (res) => {
        // console.log(res)
        var obj = this.data.style_img
        res.data.msg.forEach((v,i)=>{
          obj[i].like = v.likes
          obj[i].style = ''
        })
        this.setData({
          first: this.data.datas[0],
          data: res.data.msg,
          style_img:obj
          // data:this.data.datas.splice(1)
        })
      }
    })
  },

  onLoad: function (options) {

    // wx.onSocketMessage(data => {
    //   var obj = JSON.parse(data.data)
    //   var msg = JSON.parse(obj.msg)
    //   console.log(msg)
    //   this.setData({
    //     brange_msg: msg.nickName + ":" + msg.msg
    //   })
    // })

    /* 初次进入获取本地缓存，如果本地缓存存在，就表示之前已经授权过，
    就需要在现实授权按钮，页面就直接进入index */
    wx.getStorage({
      key: 'user',
      success: (res) => {
        console.log(res, 67);
        if (res.errMsg == "getStorage:ok") {
          this.setData({
            isLogin: true,
            avatar: res.data.avatarUrl,
            nickName: res.data.nickName
          })
        }
      }
    })
  },

  bindGetUserInfo(e) {
    this.setData({
      isLogin: true,
      avatar: e.detail.userInfo.avatarUrl,
      nickName: e.detail.userInfo.nickName
    })

    /* 点击按钮就发送请求获取用户的uid,将用户uid存储为超全局变量 */
    wx.request({
      method: "POST",
      url: 'https://www.klxin.cn/api/v1/auth',
      //url: 'http://127.0.0.1/api/v1/auth', // 仅为示例，并非真实的接口地址
      data: {
        nickName: e.detail.userInfo.nickName,
        avatarUrl: e.detail.userInfo.avatarUrl,
        gender: e.detail.userInfo.gender,
      },
      success(res) {
        // console.log(res,77);
        // console.log(e.detail.userInfo, 8989);
        e.detail.userInfo.uid = res.data.uid
        wx.setStorage({
          key: 'user',
          data: e.detail.userInfo
        });
        // app.globalData.uid   d'd= res.data.uid;
        app.globalData.userInfo = e.detail.userInfo;
        app.globalData.uid = res.data.uid;


        var obj = {
          nickName: e.detail.userInfo.nickName,
          gender: e.detail.userInfo.gender,
          avatarUrl: e.detail.userInfo.avatarUrl,
          uid: res.data.uid,
          msg: '这是授权进入的',
          flag: 1
        }
        console.log(obj, 444);
        /* 判断用户到底是发送弹幕建立的websocket还是初次进入时授权建立websocket，
        如果flag等于1说明是授权进入的，那么就建立连接显示用户图像*/
        if (obj.flag == 1 && res.data.msg !== "已签到过，重新签到成功") {
          obj.isLogin = 1
          wx.sendSocketMessage({
            data: JSON.stringify(obj),
          })
        }
      }
    })
  },

  // heart
  onUnload: function () {
    if (timer != null) {
      clearTimeout(timer);
    }
  },

  /*
   * 绘制小红心
   */
  draw: function (data) {
    var p10 = data[0][0]; // 三阶贝塞尔曲线起点坐标值
    var p11 = data[0][1]; // 三阶贝塞尔曲线第一个控制点坐标值
    var p12 = data[0][2]; // 三阶贝塞尔曲线第二个控制点坐标值
    var p13 = data[0][3]; // 三阶贝塞尔曲线终点坐标值

    var p20 = data[1][0];
    var p21 = data[1][1];
    var p22 = data[1][2];
    var p23 = data[1][3];

    var p30 = data[2][0];
    var p31 = data[2][1];
    var p32 = data[2][2];
    var p33 = data[2][3];

    var t = factor.t;

    /*计算多项式系数 （下同）*/
    var cx1 = 3 * (p11.x - p10.x);
    var bx1 = 3 * (p12.x - p11.x) - cx1;
    var ax1 = p13.x - p10.x - cx1 - bx1;

    var cy1 = 3 * (p11.y - p10.y);
    var by1 = 3 * (p12.y - p11.y) - cy1;
    var ay1 = p13.y - p10.y - cy1 - by1;

    var xt1 = ax1 * (t * t * t) + bx1 * (t * t) + cx1 * t + p10.x;
    var yt1 = ay1 * (t * t * t) + by1 * (t * t) + cy1 * t + p10.y;

    /** ---------------------------------------- */
    var cx2 = 3 * (p21.x - p20.x);
    var bx2 = 3 * (p22.x - p21.x) - cx2;
    var ax2 = p23.x - p20.x - cx2 - bx2;

    var cy2 = 3 * (p21.y - p20.y);
    var by2 = 3 * (p22.y - p21.y) - cy2;
    var ay2 = p23.y - p20.y - cy2 - by2;

    var xt2 = ax2 * (t * t * t) + bx2 * (t * t) + cx2 * t + p20.x;
    var yt2 = ay2 * (t * t * t) + by2 * (t * t) + cy2 * t + p20.y;


    /** ---------------------------------------- */
    var cx3 = 3 * (p31.x - p30.x);
    var bx3 = 3 * (p32.x - p31.x) - cx3;
    var ax3 = p33.x - p30.x - cx3 - bx3;

    var cy3 = 3 * (p31.y - p30.y);
    var by3 = 3 * (p32.y - p31.y) - cy3;
    var ay3 = p33.y - p30.y - cy3 - by3;

    /*计算xt yt的值 */
    var xt3 = ax3 * (t * t * t) + bx3 * (t * t) + cx3 * t + p30.x;
    var yt3 = ay3 * (t * t * t) + by3 * (t * t) + cy3 * t + p30.y;
    factor.t += factor.speed;
    ctx.drawImage("../../images/heart1.png", xt1, yt1, 30, 30);
    ctx.drawImage("../../images/heart2.png", xt2, yt2, 30, 30);
    ctx.drawImage("../../images/heart3.png", xt3, yt3, 30, 30);
    ctx.draw();
  },

  drawImage: function (data) {
    // 每次点小红心时先将位置回归到起点
    this.draw(data)

    // 如果到达指定位置了,小红心位置需要回归
    if (factor.t > 1) {
      factor.t = 0;
      clearTimeout(timer)
      this.draw([
        [{
          x: 30,
          y: 400
        }, {
          x: 70,
          y: 300
        }, {
          x: -50,
          y: 150
        }, {
          x: 30,
          y: 0
        }],
        [{
          x: 30,
          y: 400
        }, {
          x: 30,
          y: 300
        }, {
          x: 80,
          y: 150
        }, {
          x: 30,
          y: 0
        }],
        [{
          x: 30,
          y: 400
        }, {
          x: 0,
          y: 90
        }, {
          x: 80,
          y: 100
        }, {
          x: 30,
          y: 0
        }]
      ])
    } else {
      // 使用定时器重复绘制通过贝塞尔曲线绘制小红心动画
      timer = setTimeout(() => {
        this.drawImage([
          [{
            x: 30,
            y: 400
          }, {
            x: 70,
            y: 300
          }, {
            x: -50,
            y: 150
          }, {
            x: 30,
            y: 0
          }],
          [{
            x: 30,
            y: 400
          }, {
            x: 30,
            y: 300
          }, {
            x: 80,
            y: 150
          }, {
            x: 30,
            y: 0
          }],
          [{
            x: 30,
            y: 400
          }, {
            x: 0,
            y: 90
          }, {
            x: 80,
            y: 100
          }, {
            x: 30,
            y: 0
          }]
        ])
      }, 16.7)
    }
  },

  // 点击小红心开始动画
  onClickImage: function (e) {

    if(this.data.fetchok){
      this.data.fetchok = false
      wx.request({
        method: 'post',
        url: 'https://www.klxin.cn/api/v1/programlike',
        data: {
          id: e.target.dataset.pid,
          count: 1
        },
        success: (res) => {
          this.data.fetchok = true
          console.log(res)
        }
      })
    }

    // 如果加这句，快速点击时就看不到很多小红心(根据情况取舍)
    // clearTimeout(timer)

    if (current_ctx) {
      // console.log(current_ctx)
      current_ctx.clearRect(0, 0, 200, 600)
      current_ctx.draw()
      ctx = null
    }

    ctx = wx.createCanvasContext('canvas_wi' + e.target.dataset.cid)

    current_ctx = ctx

    this.startTimer(e.target.dataset.cid)
    
  },

  startTimer(index) {
    // 点击小红心放大效果
    var heart_style = {...this.data.style_img}
    let like = heart_style[index].like
    like++
    heart_style[index] = {
      style: 'transform:scale(1.5);',
      like:like
    }
    
    this.setData({
      style_img: heart_style
    })
    heart_style[index] = {
      style: 'transform:scale(1);',
      like
    }

    setTimeout(() => {
      this.setData({
        style_img: heart_style
      })
    }, 500)

    // 传入初始位置
    this.drawImage([
      [{
        x: 30,
        y: 400
      }, {
        x: 70,
        y: 300
      }, {
        x: -50,
        y: 150
      }, {
        x: 30,
        y: 0
      }],
      [{
        x: 30,
        y: 400
      }, {
        x: 30,
        y: 300
      }, {
        x: 80,
        y: 150
      }, {
        x: 30,
        y: 0
      }],
      [{
        x: 30,
        y: 400
      }, {
        x: 0,
        y: 90
      }, {
        x: 80,
        y: 100
      }, {
        x: 30,
        y: 0
      }]
    ])
  }
})